package org.iblink.gui.swing.views;

import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.dnd.Autoscroll;

import javax.swing.JTree;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

import org.iblink.gui.swing.IBlinkContext;
import org.iblink.gui.swing.views.component.CategoryNode;

/**
 * A tree to display, browse and manage categories.
 * 
 * @author tpares
 *
 */
public class CategoryTree extends JTree implements Autoscroll {

  /**
   * Generated serial version UID
   */
  private static final long serialVersionUID = 1740160628166222056L;
  
  /**
   * Margin for auto-scrolling
   */
  private int margin = 12;

  /**
   * Category tree constructor
   */
  public CategoryTree() {
    super(new DefaultTreeModel(new CategoryNode("Categories")));
    
    IBlinkContext.getCategoryTreeManager().initTree(this);
  }
  
  public boolean isPathEditable(TreePath path) {
    //return ((CategoryNode)path.getLastPathComponent()).isEditable();
    return !((CategoryNode)path.getLastPathComponent()).isRoot();
  }

  public void autoscroll(Point p) {
    int realrow = getRowForLocation(p.x, p.y);
    Rectangle outer = getBounds();
    realrow = (p.y + outer.y <= margin ? realrow < 1 ? 0 : realrow - 1
        : realrow < getRowCount() - 1 ? realrow + 1 : realrow);
    scrollRowToVisible(realrow);
  }

  public Insets getAutoscrollInsets() {
    Rectangle outer = getBounds();
    Rectangle inner = getParent().getBounds();
    return new Insets(inner.y - outer.y + margin, inner.x - outer.x
        + margin, outer.height - inner.height - inner.y + outer.y
        + margin, outer.width - inner.width - inner.x + outer.x
        + margin);
  }
}
